package com.example.config;

import com.example.config.filter.MyFilter;
import com.example.config.listener.MyListener;
import com.example.config.servlet.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 常用配置
 */
@Configuration
public class WebConfig {

    /**
     * 使用 FilterRegistrationBean 注册 MyFilter 过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean myFilter() {
        // 新建过滤器注册类
        FilterRegistrationBean registration = new FilterRegistrationBean();
        // 设置名称
        registration.setName("myFilter");
        // 添加自定义 过滤器
        registration.setFilter(new MyFilter());
        // 设置过滤器的URL模式
        registration.addUrlPatterns("/*");
        return registration;
    }

    /**
     * 使用 ServletRegistrationBean 注册 MyServlet
     */
    @Bean
    public ServletRegistrationBean myServlet() {
        ServletRegistrationBean registration = new ServletRegistrationBean();
        registration.setServlet(new MyServlet());
        registration.addInitParameter("name", "chengxumiao");
        registration.addInitParameter("website", "http//www.ibloger.net");
        registration.addUrlMappings("/api/my/servlet");
        return registration;
    }

    /**
     * 使用 ServletListenerRegistrationBean 注册 myListener
     */
    @Bean
    public ServletListenerRegistrationBean myListener() {
        ServletListenerRegistrationBean registration = new ServletListenerRegistrationBean();
        registration.setListener(new MyListener());
        return registration;
    }



}
